package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author xunyuhua
 * @since 2022-06-28
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Autowired
    @Lazy    // 解决循环依赖问题
    private IAuditService auditService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {
        // 从本地线程中获取当前的用户id
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();

        //状态
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //开始时间
        if (dto.getBeginPubDate() != null) {
            queryWrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate());
        }

        //结束时间
        if (dto.getEndPubDate() != null) {
            queryWrapper.le(WmNews::getPublishTime, dto.getEndPubDate());
        }

        //频道
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //关键字
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //隐藏条件：1、排序 2、当前登录人
        queryWrapper.eq(WmNews::getUserId, user.getUserId());
        queryWrapper.orderByDesc(WmNews::getPublishTime);

        //分页查询
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        Page<WmNews> page1 = this.page(page, queryWrapper);
        return new PageResponseResult(dto.getPage(), dto.getSize(), page1.getTotal(), page1.getRecords());

    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        // 从本地线程中获取当前的用户id
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断是否有id
        if (dto.getId() != null) {
            //根据自媒体文章id，删除已关联的素材关系
            deleteRelation(dto.getId());
        }
        //开始构建自媒体文章对象
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        //dto中的images是集合，表中要的是一个字符串
        wmNews.setImages(JSON.toJSONString(dto.getImages()));

        //从内容中获取所有图片
        List<ImageDto> contentImages = getImagesFromContent(dto.getContent());

        if (dto.getType() == -1) {
            //方面图片是从文章内容中获取 1 3 无图
            int size = contentImages.size();
            if (size <= 0) {
                wmNews.setType(0);
            } else if (size > 0 && size < 3) {
                wmNews.setType(1);
                //截取内容图片中的一个对象作为封面
                List<ImageDto> imageDtoList = contentImages.subList(0, 1);
                wmNews.setImages(JSON.toJSONString(imageDtoList));
            } else {
                wmNews.setType(3);
                //截取内容图片中的一个对象作为封面
                List<ImageDto> imageDtoList = contentImages.subList(0, 3);
                wmNews.setImages(JSON.toJSONString(imageDtoList));
            }
        }

        //新增文章或者修改文章，自动判断是否有id 如果有ID就是修改，如果没有id就是新增
        this.saveOrUpdate(wmNews);

        //判断是否为草稿
        if (dto.getStatus() == 1) {
            //保存文章内容图片和素材之间的关系
            saveRelation(contentImages, wmNews.getId(), 0);
            //保存文章封面图片和素材库之间关系
            List<ImageDto> imageDtoList = JSON.parseArray(wmNews.getImages(), ImageDto.class);
            saveRelation(imageDtoList, wmNews.getId(), 1);

            //完成审核
            auditService.audit(wmNews);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //1.先判断是否有文章id
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.再判断根据id是否能查询出对象
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.判断这个自媒体文章是当前登录人发布的吗
        if (user.getUserId().intValue() != wmNews.getUserId().intValue()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //4.判断文章是否为发布状态
        if (wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_UP_DOWN);
        }

        //Integer enable = dto.getEnable();
        wmNews.setEnable(dto.getEnable() == 1 ? true : false);
        this.updateById(wmNews);

        //向Kafka中放消息
        Long articleId = wmNews.getArticleId();

        Map map = new HashMap();
        map.put("articleId",articleId);
        map.put("enable",dto.getEnable() == 1 ? true : false);

        kafkaTemplate.send(upDownTopic,JSON.toJSONString(map));
        log.info("上下架后向Kafka中放入数据");

        return ResponseResult.okResult();

    }

    @Value("${topic.upDownTopic}")
    private String upDownTopic;

    private void saveRelation(List<ImageDto> imageDtoList, Integer newsId, int type) {
        int i = 0;
        for (ImageDto imageDto : imageDtoList) {
            WmNewsMaterial newsMaterial = new WmNewsMaterial();
            newsMaterial.setMaterialId(imageDto.getId());
            newsMaterial.setNewsId(newsId);
            newsMaterial.setType(type);
            newsMaterial.setOrd(i++);
            newsMaterialService.save(newsMaterial);
        }
    }

    /**
     * 从内容中获取所有图片
     *
     * @param content
     * @return
     */
    private List<ImageDto> getImagesFromContent(String content) {
        List<ImageDto> imageDtoList = new ArrayList<>();
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtoList.add(imageDto);
            }
        }
        return imageDtoList;
    }

    @Autowired
    private IWmNewsMaterialService newsMaterialService;

    /**
     * 根据自媒体文章id，删除已关联的素材关系
     *
     * @param newsId
     */
    private void deleteRelation(Integer newsId) {
        //delete from wm_news_material where news_id=?
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId, newsId);
        newsMaterialService.remove(queryWrapper);
    }
}
